<script setup>
import Header from '@/components/header/Header.vue'
import Detail from './components/Detail.vue'
import Type from './components/Type.vue'
import QRBanner from "./components/QRBanner.vue"
import {computed, ref} from "vue"
import {showConfirmDialog, showToast, showLoadingToast, closeToast} from "vant"
import { useRoute, useRouter } from "vue-router"
import api from '@/api/index.js'
import pay from '@/utils/pay.js'
import BookingPolicy from "@/components/booking-policy/BookingPolicy.vue";
import { formatTime } from "@/utils/time.js"
import {shouldHideBtn} from "@/utils/wx-utils.ts";

const fileUrl = import.meta.env.VITE_FILE_URL

// 真实的 订单状态：0-待付款 1-待发货/待核销/待制作 2-待收货  3-已完成/已核销  4-退款中  5-已退款  6-已取消  7-已发货 8-主动退款
const route = useRoute()
const router = useRouter()


const type = route.query.type


const data = ref({})
const loading = ref(false)
const name = ref('')
const _getOrderInfo = () => {
  loading.value = true
  if(type === "scenic") {
    api.getOrderInfo({
      orderNumber: route.params.id
    }).then((res) => {
      data.value = res.data
      name.value = res.data.shopName || res.data.merchantName
      data.value.memberCardVoList = data.value?.memberCardVoList?.filter((item) => item)
    }).finally(() => {
      loading.value = false
    })
  } else if (type === "hotel") {
    api.getOrderInfohotel({
      orderNumber: route.params.id
    }).then((res) => {
      data.value = res.data
      data.value.memberCardVoList = data.value?.memberCardVoList?.filter((item) => item)
      name.value = res.data?.spuListVos?.[0]?.orderSkuVo?.skuName
    }).finally(() => {
      loading.value = false
    })
  } else {
    api.getCateringOrderInfo({
      orderNumber: route.params.id
    }).then((res) => {
      data.value = res.data
      name.value = `${res.data.merchantName}${res.data.spuListVos[0].spuName}`
    }).finally(() => {
      loading.value = false
    })
  } 

}

_getOrderInfo()

const beforeClose = (action) => {
  if (action === 'cancel') {
    return true
  }
  return new Promise((resolve) => {
    api.getcancel({
      orderNumber: data.value.orderNumber
    }).then(() => {
      _getOrderInfo()
      resolve(true)
    }).catch(() => {
      resolve(false)
    })
  })
}
const handeldelorder = () => {
  showConfirmDialog({
    message: '确定取消该订单?',
    beforeClose
  })
}


// 继续支付
// pay.getPayld({ orderNumber: res.data })
function handelnewpay(id) {
  if (type === 'scenic') {
    pay.getPayld({ orderNumber: id, type: 'mini',
      finishUrl: shouldHideBtn() ? null : window.location.origin+'/#'+ `activity-order/${id}`
    })

  } else if (type === 'hotel') {
    pay.getPayld({ orderNumber: id, type: 'hotel',
      finishUrl: shouldHideBtn() ? null : window.location.origin+'/#'+ `activity-order/${id}`
    })

  } else if (type === 'hotPot') {
    // pay.getPayld({ orderNumber: id, type: 'hotel' })

  }
  pay.getPayld({ orderNumber: id, type: 'hotel' ,
    finishUrl: shouldHideBtn() ? null : window.location.origin+'/#'+ `activity-order/${id}`
  })
}


const refundClick = () => {
  if (data.value.spuListVos[0].refundType === '0') {
    showToast('该订单不可退款')
    return
  }
  router.push({
    path: `/scenic/refund/${route.params.id}`,
    query: { type }
  })
}

const goScenicDetailClick = () => {
  if (type === 'scenic') {
    router.push(`/scenicspot/${data.value.shopId}`)
  }
  if (type === 'hotel') {
    router.push(`/hotel-detail/${data.value.scenicSpotEntity.id}`)
  }
  if (type === 'hotPot') {
    router.push(`/hotpot/${data.value.scenicSpotEntity.id}`)
  }
}

const useQR = () => {
  const activeNames = ref(['1'])
  const isShowQR = ref(false)
  const openQRClick = () => {
    isShowQR.value = !isShowQR.value
    if (isShowQR.value) {
      activeNames.value = []
    } else {
      activeNames.value = ['1']
    }
  }
  return {
    activeNames, isShowQR, openQRClick
  }
}

const {activeNames, isShowQR, openQRClick} = useQR()

const useBookingPolicyPopup = () => {
  const popupShow = ref(false)
  const bookingInstructionsClick = () => {
    popupShow.value = true
  }

  const bookingPolicyClose = () => {
    popupShow.value = false
  }

  return { popupShow,bookingInstructionsClick, bookingPolicyClose }
}

const { popupShow, bookingInstructionsClick, bookingPolicyClose } = useBookingPolicyPopup()

const showButton = computed(() => {
  if (type === 'scenic' || type === 'hotel') {
    return [0, 1, 4].includes(data.value?.status)
  }
  return false
})

const revokeRefundClick = () => {
  showLoadingToast({
    message: '撤销中...',
    forbidClick: true,
    duration: 0
  })
  let getCancelRefund
  if (type === 'scenic') {
    getCancelRefund = api.getScenicCancelRefund
  } else {
    getCancelRefund = api.getHotelCancelRefund
  }
  getCancelRefund({refundNumber: data.value.refundNumber}).then((res) => {
    if (res.code === '200') {
      closeToast()
      _getOrderInfo()
      showToast('操作成功')
    }
  })
}


</script>

<template>
  <div class="order_detail">
    <Header title="订单详情" :back="true" />
    <div class="content" :class="{content_bottom: showButton}">
      <Type :loading="loading" :data="data" :type="type" />
      <div class="card" :data="data">
        <div class="card_content">
          <template v-if="!loading">
            <div class="card_content_top" @click="goScenicDetailClick">
              <div class="content_right">
                <div class="top">
                  <div class="name">
                    {{ name }}
                  </div>
                  <div class="price">
                    <span class="icon">￥</span>
                    <span class="number">{{ data?.actualPrice }}</span>
                  </div>
                </div>
                <div class="bottom">
                  <template v-if="type === 'scenic'">
                    <div class="bottom_list">
                      {{ `${data?.spuListVos?.[0]?.orderSkuVo?.skuName}${data?.spuListVos?.[0]?.orderSkuVo?.buyCount}` }} 张
                    </div>
                    <div class="bottom_list bottom_list_open" v-if="data?.useTime">
                      <div
                        v-if="data.status === 0 || data.status === 1"
                      >
                        使用日期：{{ data.useTime.split(' ')[0] }}
                      </div>
                      <div v-else>
                        过期时间：{{data.useTime}}
                      </div>
                      <div v-if="data?.status === 1" class="open" @click.stop="openQRClick">
                        {{isShowQR ? '展开' : '收起'}}
                        <van-icon v-if="isShowQR" name="arrow-down" />
                        <van-icon v-else name="arrow-up" />
                      </div>
                    </div>
                  </template>
                  <template v-if="type === 'hotel'">
                    <div
                      class="bottom_list"
                      v-if="data?.useTime"
                      :class="{'expiring_soon' : formatTime(data.useTime).isExpiringSoon}"
                    >
                      {{ formatTime(data.useTime, '有效期至').name }}
                    </div>
                    <div class="bottom_list bottom_list_open">
                      <div @click.stop="bookingInstructionsClick">
                        <template v-if="data.reservationGuidelines?.length">
                          <span class="booking_instructions">使用须知</span>
                          <van-icon name="arrow" />
                        </template>
                      </div>
                      <div v-if="data?.status === 1" class="open" @click.stop="openQRClick">
                        {{isShowQR ? '展开' : '收起'}}
                        <van-icon v-if="isShowQR" name="arrow-down" />
                        <van-icon v-else name="arrow-up" />
                      </div>
                    </div>
                  </template>
                  <template v-if="type === 'hotPot'">
                    <div class="bottom_list" v-if="data?.useTime">有效期至: {{ data.useTime }}</div>
                    <div class="bottom_list bottom_list_open">
                      <div
                        @click.stop="bookingInstructionsClick"
                        v-if="data.reservationGuidelines?.length || data.spuListVos[0].productDetail"
                      >
                        <span class="booking_instructions">使用须知</span>
                        <van-icon name="arrow" />
                      </div>
                      <div v-if="data?.status === 1" class="open" @click.stop="openQRClick">
                        {{isShowQR ? '展开' : '收起'}}
                        <van-icon v-if="isShowQR" name="arrow-down" />
                        <van-icon v-else name="arrow-up" />
                      </div>
                    </div>
                  </template>
                </div>
              </div>
              <van-image class="van_image" width="8rem" height="8rem" fit="cover" :src='`${fileUrl}/${data?.spuListVos?.[0].imageId}`' />
            </div>
            <van-collapse v-model="activeNames" :border="false">
              <van-collapse-item name="1" :is-link="false">
                <template #title></template>
                <QRBanner
                  :data="data"
                  v-if="data?.status === 1 && data.orderTicketListVos.length"
                  class="qr_banner_components"
                />
              </van-collapse-item>
            </van-collapse>
          </template>
          <van-skeleton v-else>
            <template #template>
              <div :style="{ display: 'flex', width: '100%' }">
                <van-skeleton-image />
                <div :style="{ flex: 1, marginLeft: '16px' }">
                  <van-skeleton-paragraph row-width="60%" />
                  <van-skeleton-paragraph />
                  <van-skeleton-paragraph />
                  <van-skeleton-paragraph />
                </div>
              </div>
            </template>
          </van-skeleton>
        </div>
        <Detail :data="data" :loading="loading" />
      </div>
    </div>
<!--    详情页 0-待支付 1-待使用/待发货 2-待收货 3-已完成 4-退款中 5-已退款 6-已取消-->

    <div v-if="showButton" class="bottom_button">
      <div @click="handelnewpay(data.orderNumber)" v-if="data?.status === 0" class="button primary">
        继续支付 ¥{{ data?.actualPrice }}
      </div>
      <div @click.stop="handeldelorder(data.orderNumber)" v-if="data?.status === 0" class="button default">取消订单</div>
      <div
        v-if="data?.status === 1"
        class="button default"
        :class="{button_disabled: data.spuListVos[0].refundType === '0'}"
        @click="refundClick"
      >
        申请退款
      </div>
      <div v-if="data?.status === 4" class="button default" @click="revokeRefundClick">撤销退款</div>
    </div>

    <van-popup teleport="body"  v-model:show="popupShow" round position="bottom" :style="{ 'max-height': '70vh' }">
      <BookingPolicy
        :ticketsDetailsVoList="data.reservationGuidelines"
        :refundType="data.spuListVos[0].refundType"
        :isShowBook="false"
        :productDetail="data.spuListVos[0].productDetail"
        @bookingPolicyClose="bookingPolicyClose"
      />
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
:deep(.van-cell) {
  padding: 0;
}
:deep(.van-skeleton){
  padding: 0;
}
.order_detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  //overflow-y: auto;

  .content {
    flex: 1;
    overflow-y: auto;
    background-color: #F9F8F3;
    .card {
      margin: 1rem 1.5rem;
      padding: 1.5rem;
      background: #FFFFFC;
      box-shadow: 0 1.2rem 2rem 0 rgba(2, 95, 38, 0.05);
      border-radius: 1rem;

      .card_content {
        background: #FFFFFC;
        border-bottom: .1rem solid #EEEEEE;
        padding-bottom: 1.5rem;

        .card_content_top {
          display: flex;
          justify-content: space-between;
          flex-direction: row-reverse;
          height: 8rem;

          img {
            height: 8rem;
            width: auto;
            border-radius: .5rem;
          }

          .content_right {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            margin-left: 1rem;

            .top {
              display: flex;
              justify-content: space-between;

              .name {
                font-size: 1.6rem;
                color: #333333;
                font-weight: bold;
                line-height: 1.9rem;
                word-break: break-all;
                overflow: hidden;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
              }

              .price {
                color: #333333;
                margin-left: 1rem;
                font-weight: bold;

                .icon {
                  font-size: 1.4rem;
                }

                .number {
                  font-size: 1.8rem;
                }
              }
            }

            .bottom {
              color: #999999;
              font-size: 1.2rem;

              .bottom_list {
                display: flex;
                align-items: center;
                height: 1.7rem;
                line-height: 1.7rem;
                .expiring_soon{
                  color: #ED6316;
                }
                .booking_instructions{
                  margin-right: .2rem;
                }
                .open{
                  color: var(--van-primary-color)
                }
              }
              .expiring_soon{
                color: #ED6316;
              }
              .bottom_list_open{
                justify-content: space-between;
              }
            }
          }
        }

        .qr_banner_components {
          margin-top: 2.6rem;
        }
      }
    }
  }
  .content_bottom{
    margin-bottom: 6rem;
  }

  .bottom_button {
    display: flex;
    flex-direction: row-reverse;
    height: 6rem;
    padding: 1rem 1rem 0 0;
    box-sizing: border-box;
    position: absolute;
    bottom: 0px;
    background: #ffffff;
    width: 100%;
    .button {
      margin-left: .5rem;
      height: 3.8rem;
      line-height: 3.8rem;
      text-align: center;
      padding: 0 3rem;
      background: rgba(0, 0, 0, 0.05);
      border-radius: .5rem;
      font-size: 1.6rem;
    }
    .button_disabled {
      opacity: 0.5;
    }

    .primary {
      background-color: var(--van-primary-color);
      color: #FFFFFF;
    }

    .primary:active {
      background: #4b947f;
    }

    .default {
      background: rgba(0, 0, 0, 0.05);
      color: #666666;
    }

    .default:active {
      background: rgb(215, 214, 214)
    }
  }
}
</style>